package client;

import Mysql.ShareData;
import View.ChatWindow;
import View.GroupChatWindow;
import View.MainWindow;
import com.sun.jdi.VMMismatchException;
import function.Time;
import instruction.*;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Optional;

public class Receive implements Runnable {

    private ObjectInputStream ois;
    private boolean isRunning = true;
    private MainWindow mainWindow;
    Receive(Socket socket,MainWindow mainWindow) throws IOException {
        this.ois=new ObjectInputStream(socket.getInputStream());
        this.mainWindow=mainWindow;
    }
    private Object receive()
    {
        Object obj;
        obj = null;
        try
        {
            obj = ois.readObject();
        } catch (ClassNotFoundException | IOException e)
        {
            isRunning = false;
        }
        return obj;
    }


    @Override
    public void run()
    {
        while (isRunning)
        {
            Message message=(Message)receive();
            String type=message.getMessageType();
            Platform.runLater(() ->
            {
                    if (type.equals("User")) {
                        if(message.getUser()!=null) {
                            ShareData.UserMap.put(message.getUser().getAccount(), message.getUser());//存储个人信息
                        }
                    } else if (type.equals("userData")) {
                        ShareData.UserDataMap.put(message.getUserData().getAccount(),message.getUserData());//存储用户的所有信息
                        ShareData.LoginUser.put(message.getUserData().getAccount(), message.getUserData().getUser());//存储登录用户的信息
                    } else if (type.equals("privateChat")) {//私聊信息
                        PrivateMessage privateMessage = message.getPrivateMessage();
                        if (privateMessage.getType().equals("word") || privateMessage.getType().equals("emoticon")) {
                            for (ChatWindow chatWindow : ShareData.chatWindowList) {
                                if (chatWindow.getFriend().getMember().getAccount().equals(privateMessage.getSendAccount())) {
                                    chatWindow.getPrivateMessageData().add(message);
                                    break;
                                }
                            }
                        } else if (privateMessage.getType().equals("picture")) {
                            try {
                                InputStream input = new ByteArrayInputStream(privateMessage.getPicture());
                                File file = new File("D:\\project1\\pictureData\\" + privateMessage.getContent());
                                int temp;
                                FileOutputStream fos = new FileOutputStream(file);
                                while ((temp = input.read()) != -1) {
                                    fos.write(temp);
                                }
                                input.close();
                                fos.close();
                                File image = new File("D:\\project1\\pictureData\\" + privateMessage.getContent());
                                privateMessage.setContent("file:///" + image.getAbsolutePath());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            message.setPrivateMessage(privateMessage);
                            for (ChatWindow chatWindow : ShareData.chatWindowList) {
                                if (chatWindow.getFriend().getMember().getAccount().equals(privateMessage.getSendAccount())) {
                                    chatWindow.getPrivateMessageData().add(message);
                                    break;
                                }
                            }
                        }else if(privateMessage.getType().equals("file")){
                            Message message1=new Message("privateChat");
                            Message message2=new Message("privateChat");
                            String time=Time.getTime();
                            PrivateMessage privateMessage2=new PrivateMessage("file");
                            PrivateMessage privateMessage1=new PrivateMessage("file");
                            Alert alert=new Alert(Alert.AlertType.CONFIRMATION);
                            alert.setTitle("we chat");
                            alert.setHeaderText("您的好友给您发送了一个文件："+privateMessage.getContent());
                            alert.setContentText("是否接受？");
                            Optional<ButtonType> flag=alert.showAndWait();
                            if(flag.get()== ButtonType.OK) {
                                try {
                                    InputStream input = new ByteArrayInputStream(privateMessage.getFile());
                                    File file = new File("D:\\project1\\fileData\\" + privateMessage.getContent());
                                    int temp;
                                    FileOutputStream fos = new FileOutputStream(file);
                                    while ((temp = input.read()) != -1) {
                                        fos.write(temp);
                                    }
                                    input.close();
                                    fos.close();
                                    privateMessage1.setContent("您已经成功接受该文件：" + privateMessage.getContent());
                                    privateMessage1.setTime(time);
                                    privateMessage2.setContent("对方已经成功接受该文件：" + privateMessage.getContent());
                                    privateMessage2.setTime(time);
                                } catch (FileNotFoundException e) {
                                    privateMessage1.setContent("接受文件失败");
                                    privateMessage1.setTime(time);
                                    privateMessage2.setTime(time);
                                    privateMessage2.setContent("对方无法接受该文件");
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    privateMessage1.setContent("接受文件失败");
                                    privateMessage1.setTime(time);
                                    privateMessage2.setTime(time);
                                    privateMessage2.setContent("对方无法接受该文件");
                                    e.printStackTrace();
                                }
                            }else{
                                privateMessage1.setContent("您已经拒绝接受该文件：" + privateMessage.getContent());
                                privateMessage1.setTime(time);
                                privateMessage2.setContent("对方已经拒绝接受该文件：" + privateMessage.getContent());
                                privateMessage2.setTime(time);
                            }
                            message1.setPrivateMessage(privateMessage1);
                            message2.setPrivateMessage(privateMessage2);
                            boolean flag1=false;
                            boolean flag2=false;
                                for (ChatWindow chatWindow : ShareData.chatWindowList) {
                                    if (chatWindow.getFriend().getMember().getAccount().equals(privateMessage.getSendAccount())) {
                                        chatWindow.getPrivateMessageData().add(message1);
                                        flag1=true;
                                    }
                                    if(chatWindow.getFriend().getMember().getAccount().equals(privateMessage.getReceiveAccount())){
                                        chatWindow.getPrivateMessageData().add(message2);
                                        flag2=true;
                                    }
                                    if(flag1&&flag2){
                                        break;
                                    }
                                }
                            }
                    } else if(type.equals("groupChat")){
                        GroupMessage groupMessage=message.getGroupMessage();
                        if(groupMessage.getType().equals("word")||groupMessage.getType().equals("emoticon")){
                        for(GroupChatWindow groupChatWindow:ShareData.groupChatWindowList){
                            if(groupChatWindow.getGroup().getAccount().equals(groupMessage.getReceiver())){
                                groupChatWindow.getGroupMessageData().add(message);
                            }
                        }
                        } else if(groupMessage.getType().equals("picture")){
                            try {
                                InputStream input=new ByteArrayInputStream(groupMessage.getPicture());
                                File file=new File("D:\\project1\\pictureData\\"+groupMessage.getContent());
                                int temp;
                                FileOutputStream fos=new FileOutputStream(file);
                                while((temp=input.read())!=-1){
                                    fos.write(temp);
                                }
                                input.close();
                                fos.close();
                                File image=new File("D:\\project1\\pictureData\\"+groupMessage.getContent());
                               groupMessage.setContent("file:///"+image.getAbsolutePath());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            message.setGroupMessage(groupMessage);
                            for(GroupChatWindow groupChatWindow:ShareData.groupChatWindowList){
                                if(groupChatWindow.getGroup().getAccount().equals(groupMessage.getReceiver())){
                                    groupChatWindow.getGroupMessageData().add(message);
                                    break;
                                }
                            }
                        } else if(groupMessage.getType().equals("file")){
                            Message message1=new Message("groupChat");
                            String time=Time.getTime();
                            GroupMessage groupMessage1=new GroupMessage("file");
                            Alert alert=new Alert(Alert.AlertType.CONFIRMATION);
                            alert.setTitle("we chat");
                            alert.setHeaderText("您的好友给您发送了一个文件："+groupMessage.getContent());
                            alert.setContentText("是否接受？");
                            Optional<ButtonType> flag=alert.showAndWait();
                            if(flag.get()== ButtonType.OK) {
                            try {
                                InputStream input = new ByteArrayInputStream(groupMessage.getFile());
                                File file = new File("D:\\project1\\fileData\\" + groupMessage.getContent());
                                int temp;
                                FileOutputStream fos = new FileOutputStream(file);
                                while ((temp = input.read()) != -1) {
                                    fos.write(temp);
                                }
                                input.close();
                                fos.close();
                                groupMessage1.setContent("您已经成功接受该文件：" + groupMessage.getContent());
                                groupMessage1.setTime(time);
                            } catch (FileNotFoundException e) {
                                groupMessage1.setContent("接受文件失败");
                                groupMessage1.setTime(time);
                                e.printStackTrace();
                            } catch (IOException e) {
                                groupMessage1.setContent("接受文件失败");
                                groupMessage1.setTime(time);
                                e.printStackTrace();
                            }
                        }else{
                            groupMessage1.setContent("您已经拒绝接受该文件：" + groupMessage.getContent());
                            groupMessage1.setTime(time);
                        }
                        message1.setGroupMessage(groupMessage1);
                        for(GroupChatWindow groupChatWindow:ShareData.groupChatWindowList)
                        {
                            if(groupChatWindow.getUser().getAccount().equals(message.getGroupMessage().getReceiver()))
                            {
                                groupChatWindow.getGroupMessageData().add(message1);
                            }
                        }
                    }
                    }else if(type.equals("group")){
                        ShareData.groupMap.put(message.getGroup().getAccount(),message.getGroup());
                    }else if(type.equals("addFriend")){
                        try {
                            ChatWindow chatWindow=new ChatWindow(mainWindow,mainWindow.getClientManager(),message.getFriend());
                            ShareData.chatWindowList.add(chatWindow);
                            mainWindow.getFriendData().add(message.getFriend());
                            Variety variety=new Variety("friend");
                            variety.setFriend(message.getFriend());
                            mainWindow.getMessageData().add(variety);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else if(type.equals("addGroup")){
                        try {
                            GroupChatWindow groupChatWindow=new GroupChatWindow(mainWindow,mainWindow.getClientManager(),mainWindow.getUserData().getUser(),message.getGroupMember().getGroup());
                            ShareData.groupChatWindowList.add(groupChatWindow);
                            mainWindow.getGroupData().add(message.getGroupMember().getGroup());
                            Variety variety=new Variety("group");
                            variety.setGroup(message.getGroupMember().getGroup());
                            mainWindow.getMessageData().add(variety);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else if(type.equals("createGroup")){
                        try {
                            GroupChatWindow groupChatWindow = new GroupChatWindow(mainWindow,mainWindow.getClientManager(),mainWindow.getUserData().getUser(),message.getCreateGroup());
                            ShareData.groupChatWindowList.add(groupChatWindow);
                            mainWindow.getGroupData().add(message.getCreateGroup());
                            Variety variety=new Variety("group");
                            variety.setGroup(message.getCreateGroup());
                            mainWindow.getMessageData().add(variety);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
